#!/usr/bin/env python
#
# Copyright 2008 Google Inc. All Rights Reserved.

"""AppEngine code to serve /stationlist and /stations URLs.
"""

import os
import logging
import wsgiref.handlers

from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.ext.webapp import template

import stationmanager


class StationListHandler(webapp.RequestHandler):
  def get(self):
    self.response.headers.add_header('cache-control', 'no-cache')
    self.response.out.write(stationmanager.GetStationListJSON())


class StationEditorHandler(webapp.RequestHandler):
  def get(self):
    user = users.get_current_user()
    self.response.headers['Content-Type'] = 'text/html'
    if user:
      nickname = user.nickname()
      logging.info('Request from user: ' + user.email())
    else:
      self.redirect(users.create_login_url(self.request.uri))
      return
    action = self.request.get('action')
    template_html = 'stations.html'
    template_values = {}
    if action:
      if not users.is_current_user_admin():
        self.response.out.write('Error: you are not an administrator')
        return
      elif action == 'edit':
        self.redirect('stations')
        return
      elif action == 'delete-station':
        stationmanager.DeleteStation(int(self.request.get('station')))
        self.redirect('stations')
        return
      elif action == 'delete-source':
        stationmanager.DeleteSource(int(self.request.get('source')))
        self.redirect('stations')
        return
      elif action == 'add-station-form':
        template_html = 'station-add.html'
      elif action == 'add-station':
        label = self.request.get('label')
        if label:
          stationmanager.CreateStation(label)
        self.redirect('stations')
        return
      elif action == 'add-source-form':
        template_html = 'source-add.html'
        station_id = self.request.get('station')
        template_values['station_id'] = station_id
        template_values['station_label'] = stationmanager.GetStationById(int(station_id)).label
      elif action == 'add-source':
        station_id = self.request.get('station')
        type = self.request.get('type')
        source = self.request.get('source')
        if source:
          station = stationmanager.GetStationById(int(station_id))
          stationmanager.AddSource(station, type, source)
        self.redirect('stations')
        return
      else:
        self.response.out.write('Error: unknown action')
        return
    template_values['nickname'] = nickname
    if users.is_current_user_admin():
      template_values['message'] = 'You are an admin. Edit with care.'
    else:
      template_values['message'] = 'You are not an admin, so <strong>you can\'t make changes</strong>.'
    template_values['stations'] = stationmanager.GetStationList()
    template_values['logout_url'] = users.create_login_url(self.request.uri)
    path = os.path.join(os.path.dirname(__file__), template_html)
    self.response.out.write(template.render(path, template_values))


def main():
  application = webapp.WSGIApplication([('/stationlist', StationListHandler),
                                        ('/stations', StationEditorHandler)],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)


if __name__ == '__main__':
  main()
